<?php

namespace App\Api\Controllers;

use App\Api\Models\TallyModel;
use App\Api\Services\StatisticsService;
use App\Helper\Utils\TimeUtil;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class StatisticsController extends BaseController
{
    public function sell(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type' =>[
                'required',
                Rule::In([1,2,3]),
            ],//时间 1-今日 2-本月 3-本季
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'type.required' => '报表时间范围不能为空',
            'type.in' => '错误的报表时间范围',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $condition[] = ['main_id','=',$this->getMainUserId()];
        $condition[] = ['out_status','=',1];
        $condition[] = ['pay_status','=',1];
        $condition[] = ['repeal_status','=',0];

        $condition1[] = ['a.main_id','=',$this->getMainUserId()];
        $condition1[] = ['a.out_status','=',1];
        $condition1[] = ['a.pay_status','=',1];
        $condition1[] = ['a.repeal_status','=',0];

        if($data['type']==1){
            $date = TimeUtil::convertDateSignToUnix();
        }elseif($data['type']==2){
            $date = TimeUtil::convertDateSignToUnix('month');
        }elseif($data['type']==3){
            $date = SELF::quarter();
        }

        return $this->success(
            StatisticsService::sell($data, $date, $condition, $condition1)
        );
    }

    /**
     * 当前季度
     * change 在 2021/11/12 10:55 创建
     * @return array
     */
    public function quarter(){
        $moth =  (int)date('m');
        if(in_array($moth,[1,2,3])){
            $startDate = strtotime(date('Y').'-01');
            $endDate = strtotime(date('Y').'-03-31 23:59:59');
        }elseif (in_array($moth,[4,5,6])){
            $startDate = strtotime(date('Y').'-04');
            $endDate = strtotime(date('Y').'-06-30 23:59:59');
        }elseif (in_array($moth,[7,8,9])){
            $startDate = strtotime(date('Y').'-07');
            $endDate = strtotime(date('Y').'-09-30 23:59:59');
        }elseif (in_array($moth,[10,11,12])){
            $startDate = strtotime(date('Y').'-10');
            $endDate = strtotime(date('Y').'-12-31 23:59:59');
        }
        return [$startDate, $endDate];
    }

    /**
     * 收入
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/6 16:07
     * @return \Illuminate\Http\JsonResponse
     */
    public function incomeOrExpend(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' =>[
                'required',
                Rule::In([0,1]),
            ],//收支类型：0-收入 1-支出
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'type.required' => '`报表类型`缺失',
            'type.in' => '`报表类型`错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
            $condition[] = ['add_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['add_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['add_time', '<=', $endTime];
        }

        $condition['type'] = ['EQ' => $data['type']];

        $condition['main_id'] = ['EQ' => $this->getMainUserId()];

        $totalInfo = TallyModel::selectRaw(
            'SUM(money) as money'
        )->where($condition)->groupBy('main_id')->first();

        $result['total_money'] = empty($totalInfo)?0:$totalInfo->money;
        $result['income_list'] = TallyModel::selectRaw(
            'add_time,money,tally_class_name'
        )->where($condition)
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $this->success($result);
    }

    /**
     * 采购报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMateriel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
            $condition[] = ['b.purchase_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['b.purchase_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['b.purchase_time', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMateriel($condition, $data)
        );
    }

    /**
     * 采购报表详情
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 19:59
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementMaterielDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_id' =>'required|integer',//商品id
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'type_id.required' => '`商品id`缺失',
            'type_id.integer' => '`商品id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.purchase_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.purchase_time', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['b.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['b.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementMaterielDetail($data, $condition)
        );
    }

    /**
     * 成本报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/8 14:57
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCost(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
            'type' =>[
                'required',
                Rule::In([0,1]),//成本报表类型:0:商品;1:套餐;
            ],
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
            'type.required' => '请选择报表类型',
            'type.in' => '报表类型错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['a.out_storage_time', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['a.out_storage_time', '<=', $endTime];
        }

        return $this->success(
            StatisticsService::statementCost($condition, $data)
        );
    }

    /**
     * 销售报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 13:43
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementSell(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'start_time' => 'nullable|date_format:Y-m-d',//开始时间
            'end_time' => 'nullable|date_format:Y-m-d',//开始时间
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'start_time.date_format' => '开始日期格式有误，例：'.date('Y-m-d'),
            'end_time.date_format' => '结束日期格式有误，例：'.date('Y-m-d'),
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        $condition = [];

        if(!empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
            $condition[] = ['sell_date', '<=', $endTime];
        }
        else if(!empty($startTime) && empty($endTime)) {
            $condition[] = ['sell_date', '>=', $startTime];
        }
        else if(empty($startTime) && !empty($endTime)) {
            $condition[] = ['sell_date', '<=', $endTime];
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementSell($condition, $data)
        );
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorage(Request $request)
    {
        $condition['main_id'] = ['EQ' => $this->getMainUserId()];

        return $this->success(
            StatisticsService::statementStorage($condition)
        );
    }

    /**
     * 仓库报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/13 16:36
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementStorageDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'storage_id.required' => '`仓库id`缺失',
            'storage_id.integer' => '`仓库id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            StatisticsService::statementStorageDetail($request->storage_id, $data)
        );
    }

    /**
     * 客户报表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:02
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function statementCustomer(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementCustomer($data, $condition)
        );
    }

    /**
     * 客户报表详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/15 14:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function statementCustomerDetail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer|min:1',//页面大小
            'currentPage' => 'required|integer',//当前页
            'customer_id' => 'required|integer',//供应商或客户id
            'customer_name' => 'required',//供应商或客户id
            'type' =>[
                'required',
                Rule::In([0,1]),
            ],//统计类型;0:采购;1:销售;
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
            'customer_id.required' => '`供应商或客户id`缺失',
            'customer_id.integer' => '`供应商或客户id`只能为数字',
            'customer_name.required' => '`供应商或客户名称`缺失',
            'type.required' => '`统计类型`缺失',
            'type.In' => '`统计类型`不合法',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            StatisticsService::statementCustomerDetail($data, $condition)
        );
    }
}
